#include "parse_lisp.h"
#include <stdlib.h>
#include <string.h>
#include "dd_dynamic_array.h"
#include "engine.h"

struct avgdl_command *parse_command(FILE *f) {
	// Buffer
	char c[1024];

	// Remove whitespace
	fscanf(f, "%*[ 	\n]");

	char *name = 0;
	struct dd_dynamic_array *args = malloc(sizeof(struct dd_dynamic_array));
	name = 0;
	dd_da_init(args, sizeof(char*));

	if ( !fscanf(f, "%[(]", c) ) {
		printf("does not start with command, error!\n");
		return 0;
	} else
	if ( feof(f)) {
		return 0;
	}

	while (!fscanf(f, "%1[)]", c)) {

		// Testing
		struct avgdl_command *cmd_arg = 0;

		// Depending on what is found

		// Remove whitespace
		if (fscanf(f, "%[ 	\n]", c)) {

		} else
		// Word
		if ( fscanf(f, "%255[a-z0-9.-]", c) ) {
			if (!name) {
				name = malloc(sizeof(char) *strlen(c));
				strcpy(name, c);
			}
			else {
				char *word = malloc(sizeof(char) *strlen(c));
				strcpy(word, c);
				dd_da_add(args, word);
			}
		} 
		else
		// Another command - recursion
		if ( cmd_arg = parse_command(f) ) {
			printf("another command: %s\n", cmd_arg->name);
//			printf("found command: %s\n", cmd_arg->name);
//			fscanf(f, "%100c", c);
//			printf("next character: %s\n", c);
//			return 0;
		}
		else {
			fscanf(f, "%1c", c);
			printf("can't recognize %c\n", c[0]);
		}

	}

	dd_da_add(args, "");

	struct avgdl_command *cmd = malloc(sizeof(struct avgdl_command));
	cmd->name = name;
	cmd->arg = (char **)args->array;
	free(args);

	return cmd;

}

// Free command
void free_command(struct avgdl_command *cmd) {
	free(cmd->name);
	free(cmd->arg);
	free(cmd);
}
